package com.spa.application.service.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spa.application.command.admin.MassagistAdminEditCommand;
import com.spa.application.dto.PageResult;
import com.spa.application.dto.admin.*;
import com.spa.application.query.admin.MassagitsFinanceQuery;
import com.spa.application.query.admin.MassagitsPageQuery;
import com.spa.application.query.admin.MassagitsServiceTimePageQuery;
import com.spa.application.query.admin.MassagitsonoffPageQuery;
import com.spa.domain.entity.MassageServiceEntity;
import com.spa.domain.entity.Massagist;
import com.spa.domain.entity.Rule;
import com.spa.domain.entity.Shop;
import com.spa.domain.service.MassageService;
import com.spa.domain.service.MassagistOnoffService;
import com.spa.domain.service.MassagistService;
import com.spa.domain.service.OrderService;
import com.spa.domain.service.RuleService;
import com.spa.domain.service.ShopService;
import com.spa.infrastructure.enums.dict.rule.RuleClassifyEnum;
import com.spa.infrastructure.exception.SpaException;
import com.spa.infrastructure.mapper.MassageServiceMapperStruct;
import com.spa.infrastructure.mapper.MassagistMapperStruct;
import com.spa.infrastructure.mapper.MassagistOnoffMapperStruct;
import com.spa.infrastructure.repository.condition.OrderInfoCondition;
import com.spa.infrastructure.repository.condition.RuleCondition;
import com.spa.infrastructure.repository.po.MassagistOnoffPO;
import com.spa.infrastructure.repository.po.MassagistPO;
import com.spa.infrastructure.repository.service.UserCollectionRepositoryService;
import com.spa.infrastructure.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class MassagistApplicationService {

    @Autowired
    private MassagistService massagistService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MassagistOnoffService massagistOnoffService;
    @Resource
    private ShopService shopService;

    @Autowired
    private MassageService massageService;

    @Resource
    private UserCollectionRepositoryService userCollectionRepositoryService;
    @Resource
    private RuleService ruleService;

    public PageResult<MassagistAdminListDTO> page(MassagitsPageQuery query) {
        Page<Massagist> massagistPage = massagistService.pageMassagistJoinShop(query);
        PageResult<MassagistAdminListDTO> massagistAdminListDTOPageResult = MassageServiceMapperStruct.INSTANCE.entity2MassagistAdminListDTO4Page(massagistPage);
        massagistAdminListDTOPageResult.getRecords().forEach(massagist -> {
            OrderInfoCondition orderInfoCondition = new OrderInfoCondition();
            orderInfoCondition.setMassagistId(massagist.getId());
            massagist.setOrderCount(orderService.countByCondition(orderInfoCondition));
            massagist.setServiceTime(massagistOnoffService.sumServiceTimeByMassagistId(massagist.getId(), null, null));
            massagist.setFollowCount(userCollectionRepositoryService.countCollectionByMassagistId(massagist.getId()));
        });
        return massagistAdminListDTOPageResult;
    }

    public List<MassagistExportDTO> list(MassagitsPageQuery query) {
        List<Massagist> massagistList = massagistService.exportList(query);
        if (massagistList != null) {
            massagistList.forEach(massagist -> {
                OrderInfoCondition orderInfoCondition = new OrderInfoCondition();
                orderInfoCondition.setMassagistId(massagist.getId());
                massagist.setSelectCount(Math.toIntExact(orderService.countByCondition(orderInfoCondition)));
                massagist.setServiceTime(massagistOnoffService.sumServiceTimeByMassagistId(massagist.getId(), null, null));
                massagist.setFollowCount(userCollectionRepositoryService.countCollectionByMassagistId(massagist.getId()));
            });
        }
        return MassagistMapperStruct.INSTANCE.dto2entity(massagistList);
    }

    public PageResult<MassagistServiceTimeDTO> onoffTimePage(MassagitsServiceTimePageQuery query) {
        Page<MassagistOnoffPO> page = massagistOnoffService.page(query);
        PageResult<MassagistServiceTimeDTO> massagistOnoffDTOPageResult = MassagistOnoffMapperStruct.INSTANCE.po2Dto4page(page);
        massagistOnoffDTOPageResult.getRecords().forEach(massagistOnoffDTO -> {
            massagistOnoffDTO.setLineDate(massagistOnoffDTO.getOnline());
            if (ObjectUtil.isNull(massagistOnoffDTO.getOffline())) {
                massagistOnoffDTO.setDuration(DateUtil.between(massagistOnoffDTO.getOnline(), new Date(), DateUnit.MINUTE));
            }
        });
        return massagistOnoffDTOPageResult;
    }

    public PageResult<MassagistOnoffDTO> onoffPage(MassagitsonoffPageQuery query) {
        PageResult<MassagistOnoffDTO> massagistOnoffDTOPageResult = massagistOnoffService.pageMassagistOnoff(query);
//        massagistOnoffDTOPageResult.getRecords().forEach(massagistOnoffDTO -> {
//            Massagist massagist = massagistService.infoById(massagistOnoffDTO.getMassagistId());
//            massagistOnoffDTO.setName(massagist.getName());
//            massagistOnoffDTO.setPhone(massagist.getPhone());
//            massagistOnoffDTO.setWorkPhoto(massagist.getWorkPhoto());
//            //获取归属门店
//            Shop shop = shopService.getShopByMassagistId(massagistOnoffDTO.getMassagistId());
//            massagistOnoffDTO.setShopName(shop.getName());
//        });
        return massagistOnoffDTOPageResult;
    }

    //技师当日 当月，总计-财务统计
    public MassagistFinanceDTO finance(MassagitsFinanceQuery query) {
        if (ObjectUtil.isNull(query.getMassagistId())) {
            throw new SpaException("缺少技师信息");
        }
        MassagistFinanceDTO massagistFinanceDTO = new MassagistFinanceDTO();
        Date date = new Date();
        String beginDate = DateUtil.beginOfDay(date).toString(DatePattern.NORM_DATETIME_FORMAT);
        String endDate = DateUtil.endOfDay(date).toString(DatePattern.NORM_DATETIME_FORMAT);
        massagistFinanceDTO.setDaily(massagistService.getMyFinanceDetails(query.getMassagistId(), beginDate, endDate));
        beginDate = DateUtil.beginOfMonth(date).toString(DatePattern.NORM_DATETIME_FORMAT);
        endDate = DateUtil.endOfMonth(date).toString(DatePattern.NORM_DATETIME_FORMAT);
        massagistFinanceDTO.setMonthly(massagistService.getMyFinanceDetails(query.getMassagistId(), beginDate, endDate));
        massagistFinanceDTO.setTotal(massagistService.getMyFinanceDetails(query.getMassagistId(), null, null));
        return massagistFinanceDTO;
    }

    @Transactional
    public void edit(MassagistAdminEditCommand command) {
        Massagist massagist = massagistService.getInfoByMassagistId(command.getMassagistId());
        MassagistPO po = MassagistMapperStruct.INSTANCE.command2Po(command);
        po.setId(command.getMassagistId());
        massagistService.editMassagist(po, command.getServiceList());

        ruleService.addMassagistRule(command.getRuleDtoList(), massagist.getShopId(), massagist.getId());
    }

    public boolean removeMassagits(Long massagistId) {
        return massagistService.removeMassagitsById(massagistId);
    }

    public MassagistAdminEditDTO queryInfo(Long massagistId) {
        Massagist massagist = massagistService.getInfoByMassagistId(massagistId);

        MassagistAdminEditDTO massagistAdminEditDTO = MassagistOnoffMapperStruct.INSTANCE.entity2Dto4massagistAdmin(massagist);
        List<ImgsDTO> lifePhotoList = new ArrayList<>();
        List.of(massagistAdminEditDTO.getLifePhoto().split(",")).forEach(img -> {
            lifePhotoList.add(ImgsDTO.builder().url(img).uid(UrlUtil.handleUrl(img, ",")).build());
        });
        massagistAdminEditDTO.setLifePhotoList(lifePhotoList);
        //获取名下项目
        List<MassageServiceEntity> massageServiceEntities = massageService.getServiceByMessageId(massagist.getId());
        if (CollectionUtil.isNotEmpty(massageServiceEntities)) {
            massagistAdminEditDTO.setServiceList(massageServiceEntities.stream().map(m -> String.valueOf(m.getId())).toList());
        }
        //获取归属门店
        Shop shop = shopService.getInfoById(massagist.getShopId());
        if (ObjectUtil.isNotEmpty(shop)) {
            massagistAdminEditDTO.setShopId(shop.getId());
            massagistAdminEditDTO.setShopName(shop.getName());
        }

        //规则
        RuleCondition ruleCondition = new RuleCondition();
        ruleCondition.setClassify(RuleClassifyEnum.$10.getCode());
        ruleCondition.setRelevanceId(massagistId);
        List<Rule> listRule = ruleService.listRule(ruleCondition);
        if (CollUtil.isNotEmpty(listRule)) {
            massagistAdminEditDTO.setRuleDtoList(Rule.listRuleToDto(listRule));
        }
        return massagistAdminEditDTO;
    }

    /**
     * 获取按摩师上下线列表的导出数据。
     *
     * @return 返回一个包含按摩师开关状态导出数据的列表。
     */
    public List<MassagistOnofExportDTO> onoffList(MassagitsonoffPageQuery query) {
        return MassagistOnoffMapperStruct.INSTANCE.entity2DTOExport(massagistOnoffService.onoffList(query));
    }
}
